/**
 * 
 */
package org.istt.dao.hibernate;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.istt.dao.GroupDao;
import org.istt.domain.Group;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.ObjectRetrievalFailureException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

/**
 * This class interacts with Spring and Hibernate to save and
 * retrieve Group objects.
 *
 * @author NDTHO
 */
@Repository(value = "group")
public class GroupDaoHibernate extends BaseDaoHibernate<Group, Long> implements GroupDao {
    Log logger = LogFactory.getLog(GroupDaoHibernate.class);
    
    @Autowired
    public GroupDaoHibernate(SessionFactory sessionFactory) {
		super(sessionFactory);
	}
    
	public List<Group> getGroups() {
        return findAll();
    }

    public Group getGroup(Long id) {
    	Group group = findById(id, false);
        if (group == null) {
            throw new ObjectRetrievalFailureException(Group.class, id);
        }
        return group;
    }
    
    @Override
    public Group getGroup(final String role,final boolean isSystem) {
    	return (Group) hibernateTemplate.execute(new HibernateCallback<Object>() {
			@Override
			public Group doInHibernate(Session session) throws HibernateException,	SQLException {
						Criteria criteria = session.createCriteria(Group.class);
						criteria.add(Restrictions.eq("authority", role));
						criteria.add(Restrictions.eq("roleSystem", isSystem));
						return (Group)criteria.uniqueResult();
			}
		});
    }

    public void saveGroup(Group group) {
        makePersistent(group);

        if (logger.isDebugEnabled()) {
            logger.debug("groupId set to: " + group.getId());
        }
    }

    public void removeGroup(Long id) {
    	makeTransient(getGroup(id));
    }

	@SuppressWarnings("unchecked")
	@Override
	public List<Group> searchGroup(final String name) {
		
		return (List<Group>) hibernateTemplate.execute(new HibernateCallback<Object>() {
			@Override
			public Object doInHibernate(Session session) throws HibernateException,	SQLException {
						Criteria criteria = session.createCriteria(Group.class);
						if(name!=null && !"".equals(name)) criteria.add(Restrictions.ilike("name", "%"+name+"%"));
						return criteria.list();
			}
		});
	}
}
